package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户提交订单
     * @param ordersSubmitDTO
     * @return
     *
     * 由于无法实现支付功能，所以用户下单成功，即设置为支付成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常（地址薄为空，购物车数据为空）
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        //判断用户地址
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //获取用户购物车
        List<ShoppingCart> list = shoppingCartMapper.select(shoppingCart);
//        判断用户购物车是否为空
        if(list == null) {
//        若用户购物车为空抛出异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1、向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setUserId(userId);
        orders.setPayStatus(Orders.PAID);
        orders.setAddress(address.getProvinceName()+
                address.getCityName()+
                address.getDistrictName());
        orderMapper.insert(orders);
        //2、向订单明细表插入n条数据
        OrderDetail orderDetail = new OrderDetail();
        List<OrderDetail> orderDetatilList = new ArrayList<>();
        list.forEach(itme -> {
            BeanUtils.copyProperties(itme, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetatilList.add(orderDetail);

        });

        orderDetailMapper.insert(orderDetatilList);
        //3.清空购物车数据
        shoppingCartMapper.delete(userId);
        //封装vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        //用户下单提醒
        Map map = new HashMap();
        map.put("type",1); // 1.表示来单提醒 2 表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

        return orderSubmitVO;
    }

    /**
     * 订单查询
     */
    @Override
    public PageResult search(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
//        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //查询订单
        Page<Orders> page = orderMapper.select(ordersPageQueryDTO);
        //查询每个订单的菜品信息
//        orderDetailMapper.select( )
        return new PageResult(page.getTotal(),page.getResult());
    }
    /**
     * 查询订单详细信息
     */
    @Override
    public Orders getById(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> list = orderDetailMapper.getById(id);
        orders.setOrderDetailList(list);
        return orders;
    }

    /**
     * 查看各个订单的状态数量
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        List<Map<String, Object>> list = orderMapper.getOrderStatusCount();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        list.forEach(item -> {
            int status =(int) item.get("status");
            Long countLong = (Long) item.get("total_count");
            // 将 Long 类型转换为 int 类型
            int count = countLong.intValue();
            switch (status){
                case 2: orderStatisticsVO.setToBeConfirmed(count);
                    break;
                case 3: orderStatisticsVO.setConfirmed(count);
                    break;
                case 4: orderStatisticsVO.setDeliveryInProgress(count);
                    break;
                default:
                    break;
            }
        });
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param id
     */
    @Override
    public void confirm(Long id) {
        orderMapper.updateOrderStatus(id,Orders.CONFIRMED,null,null);

    }
    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.updateOrderStatus(ordersRejectionDTO.getId(),Orders.CANCELLED,ordersRejectionDTO.getRejectionReason(),null);
    }
    /**
     * 取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.updateOrderStatus(ordersCancelDTO.getId(),Orders.CANCELLED,null,ordersCancelDTO.getCancelReason());
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        orderMapper.updateOrderStatus(id,Orders.COMPLETED,null,null);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        orderMapper.updateOrderStatus(id,Orders.DELIVERY_IN_PROGRESS,null,null);
    }
    /**
     * 查看用户历史订单
     */
    @Override
    public PageResult UserHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> select = orderMapper.select(ordersPageQueryDTO);
        int pageSize = select.getPageSize();
        List<Orders> list = select.getResult();
        list.forEach(item->{
            item.setOrderDetailList(orderDetailMapper.getById(item.getId()));
        });
        return new PageResult(select.getTotal(),list);
    }

    /**
     * 查询用户订单详细
     */
    @Override
    public Orders selectUserOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> byId = orderDetailMapper.getById(orders.getId());
        orders.setOrderDetailList(byId);
        return orders;
    }
    /**
     * 用户再来一单
     */
    //TODo
    @Override
    public void repetition(Long id) {
//        Orders orders = orderMapper.getById(id);
        List<OrderDetail> byId = orderDetailMapper.getById(id);
//        orders.setNumber(String.valueOf(System.currentTimeMillis()));
//        orders.setOrderTime(LocalDateTime.now());
//        orders.setPayStatus(Orders.PENDING_PAYMENT);
//        orders.setStatus(Orders.UN_PAID);
//        orders.setCancelReason(null);
//        orders.setRejectionReason(null);
//        orders.setCancelTime(null);
//        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        byId.forEach(item->{
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        });
    }

    /**
     * 催单
     */
    @Override
    public void reminder(Long id) {
        Map map = new HashMap();
        map.put("type",2);
        Orders orders = orderMapper.getById(id);
        if(orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber()+"用户催单啦");
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}
